// --------------------------------------------------
// --------------------------------------------------
// -----------author:zhoumingle----------------------
// -------------原生node 专题-------------------------—
// -------------原生node 专题--------------------------
// -------------原生node 专题-------------------------
// -------------原生node 专题-------------------------
// --------------------------------------------------
// --------------------------------------------------

const http = require('http');
// let Url = require('url');
let path = require("path");
let fs = require('fs');
const querystring = require('querystring');

// 1、创建问服务
let app = http.createServer();
//2、监听请求
app.on('request', async (req, res) => {
    let {url, method} = req;
    const myURL = new URL(url.toString(), 'http://localhost:3000/');
    let name = myURL.searchParams.get('name') || 'init';
    let pathname = myURL.pathname;
    let realpath =path.join(__dirname, pathname);
    // console.log(myURL);
    // 设置响应头
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8',
    });

    if (method.toLowerCase() === 'get') {
        // console.log('请求get！'+ name);
        if(pathname == '/user') {
            setTimeout(_ =>{
                res.end(name);
            },2000);
        }
        else if (pathname == '/delay') {
            setTimeout(_ =>{
                res.end(name);
            },6000);
        }
        else {
            fs.readFile(realpath, (err, data) => {
                if (err) throw err;
                res.end(data);
            });
        }
    }
    else if (method.toLowerCase() === 'post') {
        if (pathname === '/postdata') {
            // res.end('请求post！');
            let formatData = '';
            req.on('data', function (data) { 
                formatData += data;
            });
            req.on('end', () => {
                // let res1 = querystring.parse(formatData);
                // console.log('formatData', res1)
                res.end('post 请求收到啦:' + formatData);
            })
        }
    }
    else {
        res.end('请求发生未知错误！');
    }
})
// 3、监听端口
app.listen(3000, function (param) {  
    console.log('服务器启动成功，端口3000');
});
